﻿using System;
using System.IO;
using System.Web;
using Flagwind.Plugins;
using Flagwind.ComponentModel;
using Flagwind.Options.Configuration;

namespace Flagwind.Web.Plugins
{
	public class ApplicationContext : PluginApplicationContext
	{
		#region 单例字段

		public new static readonly ApplicationContext Current = new ApplicationContext();

		#endregion

		#region 成员字段

		private string _applicationDirectory;
		private OptionConfiguration _configuration;

		#endregion

		#region 公共属性

		/// <summary>
		/// 获取当前Web应用程序的上下文对象。
		/// </summary>
		public HttpContext HttpContext
		{
			get
			{
				return HttpContext.Current;
			}
		}

		public override string ApplicationDirectory
		{
			get
			{
				if(string.IsNullOrEmpty(_applicationDirectory))
					_applicationDirectory = HttpContext.Current.Server.MapPath("~");

				return _applicationDirectory;
			}
		}

		public override Flagwind.Options.Configuration.OptionConfiguration Configuration
		{
			get
			{
				if(_configuration == null)
				{
					string filePaht = Path.Combine(this.ApplicationDirectory, "Web.option");

					if(File.Exists(filePaht))
						_configuration = Options.Configuration.OptionConfiguration.Load(filePaht);
					else
						_configuration = new Options.Configuration.OptionConfiguration(filePaht);
				}

				return _configuration;
			}
		}

		public override System.Security.Principal.IPrincipal Principal
		{
			get
			{
				return HttpContext.Current.User;
			}
			set
			{
				HttpContext.Current.User = value;
			}
		}

		#endregion

		#region 私有构造

		private ApplicationContext() : base("Flagwind.Web.Plugins")
		{
			ApplicationContextBase.Current = this;
		}

		#endregion

		#region 重写方法

		protected override IWorkbenchBase CreateWorkbench(string[] args)
		{
			PluginTreeNode node = this.PluginContext.PluginTree.Find(this.PluginContext.Settings.WorkbenchPath);

			if(node != null && node.NodeType == PluginTreeNodeType.Builtin)
				return base.CreateWorkbench(args);

			return new Workbench(this);
		}

		#endregion
	}
}
